package com.itheima.bakery.demos.web.controller;

import com.itheima.bakery.demos.web.Utility.CookieUtils;
import com.itheima.bakery.demos.web.model.LoginRequest;
import com.itheima.bakery.demos.web.model.LoginResponse;
import com.itheima.bakery.demos.web.model.Order;
import com.itheima.bakery.demos.web.model.User;
import com.itheima.bakery.demos.web.service.UserService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@CrossOrigin(origins="*")
@RestController
@RequestMapping("/users")
public class UserController {

    private final UserService userService;
    private final PasswordEncoder passwordEncoder;
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    public UserController(UserService userService, PasswordEncoder passwordEncoder) {
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
    }

    @GetMapping
    public List<User> listUsers() {
        return userService.findAllUsers();
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Integer id) {
        return userService.findUserById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.saveUser(user);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Integer id) {
        userService.deleteUser(id);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/login")
    public ResponseEntity<?> loginUser(@RequestBody LoginRequest loginRequest, HttpServletResponse response) {
        String inputPassword = loginRequest.getPassword();
        Optional<User> userOptional = userService.findUserByEmail(loginRequest.getEmail());

        if (userOptional.isEmpty()) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Email not found");
        }

        User user = userOptional.get();
        // 直接比较明文密码
        boolean isPasswordMatch = inputPassword.equals(user.getPassword());

        if (!isPasswordMatch) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Password incorrect");
        }

        // 生成JWT或其他认证令牌
        String token = generateToken(user);

        // 设置用户ID的Cookie
        Cookie userIdCookie = new Cookie("user_id", String.valueOf(user.getUserID()));
        userIdCookie.setHttpOnly(true);
        userIdCookie.setPath("/");
        userIdCookie.setMaxAge(60 * 60 * 24 * 7); // 7天有效期
        response.addCookie(userIdCookie);

        // 设置认证令牌的Cookie
        Cookie tokenCookie = new Cookie("auth_token", token);
        tokenCookie.setHttpOnly(true);
        tokenCookie.setPath("/");
        tokenCookie.setMaxAge(60 * 60 * 24 * 7); // 7天有效期
        response.addCookie(tokenCookie);

        // 创建登录成功的响应对象
        LoginResponse loginResponse = new LoginResponse(user.getUserID(), token);
        return ResponseEntity.ok(loginResponse);
    }






    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable Integer id, @RequestBody User userRequest) {
        return userService.findUserById(id)
                .map(user -> {
                    user.setName(userRequest.getName());
                    user.setEmail(userRequest.getEmail());
                    user.setContactInfo(userRequest.getContactInfo());
                    user.setAddress(userRequest.getAddress());
                   user.setPassword(userRequest.getPassword());
                    return ResponseEntity.ok(userService.saveUser(user));
                })
                .orElse(ResponseEntity.notFound().build());
    }

    private String generateToken(User user) {
        // 使用JWT或其他方式生成认证令牌
        // 这里只是一个示例
        return "some-token-generated-for-" + user.getEmail();
    }
    @GetMapping("/my-endpoint")
    public String myEndpoint(HttpServletRequest request) {
        return CookieUtils.getUserIdCookie(request)
                .map(userId -> "User ID: " + userId)
                .orElse("No user ID cookie found");
    }

    @GetMapping("/get-user-info")
    public ResponseEntity<User> getUserInfo(@RequestParam Integer userId) {
        User user = userService.findUserById(userId)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found"));
        return ResponseEntity.ok(user);
    }

    @GetMapping("/get-orders")
    public ResponseEntity<List<Order>> getOrders(@RequestParam Integer userId) {
        List<Order> orders = userService.findOrdersByUserId(userId);
        return ResponseEntity.ok(orders);
    }
    @GetMapping("/logout")
    public String go_index(
            HttpServletRequest request,
            HttpServletResponse response){
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("token",null);
        cookie.setMaxAge(0);//设置存活时间，“0”即马上消失
        cookie.setPath("/");
        response.addCookie(cookie);
        return "redirect:/";
    }

}